﻿using MediatR;
using RBAC.Common.Domains;
using RBAC.Common.Dto;
using RBAC.Common.infrastructures.interfaces;
using RBAC.Enum;

namespace RBAC.api.Application.commond.RBAC
{
    public class UserHtmlHander : IRequestHandler<UserHtmlCommond, Rulst>
    {



        private readonly IbaseRpository<Role> _role;

        private readonly IbaseRpository<RolePermission> _rolepersion;

        private readonly IbaseRpository<Permission> _perssion;

        public UserHtmlHander(IbaseRpository<Role> role, IbaseRpository<RolePermission> rolepersion, IbaseRpository<Permission> perssion)
        {
            _role = role;
            _rolepersion = rolepersion;
            _perssion = perssion;
        }

        public async Task<Rulst> Handle(UserHtmlCommond request, CancellationToken cancellationToken)
        {

       


            var result = new Rulst() { Code = (int)Reult.success };


            var query= new HtmlGET { Count=0,NEW=new List<USerRoleDto>(),Page=0};


             query.NEW = (from a in _role.Query()
                        join b in _rolepersion.Query() on a.Roleid equals b.Roleid
                        select new USerRoleDto()
                        {
                           username=a.RoleName,
                           Status=a.isyes,
                           userid=a.Roleid,
                            gh = new List<gesd>(),
                        }).Distinct().ToList();

            var PUTUSerRoleDto = query.NEW;


 
            if (query!=null)
            {
                foreach (var item in PUTUSerRoleDto)
                {

                    item.gh = (from a in _rolepersion.Query()
                                     join b in _perssion.Query() on a.Permissionid equals b.Permissionid
                                     where a.Roleid == item.userid
                                     select new gesd()
                                     {
                                        RoleName= b.PermissionName
                                     }).Distinct().ToList();
                }
            }


            //多杀条
            query.Count = PUTUSerRoleDto.Count;
            //多少页
            query.Page = (int)Math.Ceiling(PUTUSerRoleDto.Count * 1.0 / request.PageSize);

            var num=(request.Pageinex-1)*request.PageSize;
            
            query.NEW = PUTUSerRoleDto.OrderBy(x => x.userid).Skip(num).Take(request.PageSize).ToList();



            result.data = query;


            return result;

           




        }
    }
}
